<template>
  <div>
    <div class="self-box">
      <Card class="smart-query-card">
        <!------ 查询条件第一行 begin------->
        <Row class="smart-query-form-row">
          <Form :model="searchForm" class="tools" inline ref="searchForm">
            <FormItem>
              <Select
                style="width: 200px"
                placeholder="Please choose approval status"
                v-model="searchForm.publishStatus"
              >
                <Option value="">All</Option>
                <Option v-for="item in publishStatusList" :key="item" :value="item.configKey">{{item.configValue}}</Option>
              </Select>
            </FormItem>
            <FormItem prop="label">
              <Input
                placeholder="Please insert label"
                type="text"
                v-model="searchForm.tag"
              />
            </FormItem>
            <FormItem prop="title">
              <Input
                placeholder="Please insert asset name"
                type="text"
                v-model="searchForm.name"
              />
            </FormItem>
            <FormItem prop="categoryId">
              <treeselect
                v-model="searchForm.categoryId"
                :options="options1"
                id="id"
                placeholder="Select Category"
                :load-options="loadOptions"
              />
            </FormItem>
            <FormItem>
              <ButtonGroup>
                <Button
                  @click="find"
                  icon="ios-search"
                  type="primary"
                  v-privilege="'assets-list-query'"
                  >Search</Button
                >
              </ButtonGroup>
            </FormItem>
          </Form>
        </Row>
      </Card>
      <Card class="warp-card">
        <!-------操作按钮行 begin------->
        <Row class="marginBottom10">
          <Button
            @click="showAddTypeForm"
            class="marginLeft10"
            type="primary"
            size="small"
            v-privilege="'assets-category-batch-select'"
            >Batch Select Category</Button
          >
          <Button
            @click="showAddLabelForm"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'assets-tags-batch-update'"
            >Batch Select Label</Button
          >
          <Button
            @click="batchDownload"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'assets-batch-download'"
            >Batch Download</Button
          >
          <Button
            @click="showBatchDeleteModal"
            type="primary"
            class="marginLeft10"
            size="small"
            v-privilege="'assets-batch-audit'"
            >Batch Approve</Button
          >
          <Button
            @click="deleteEmail"
            class="marginLeft10"
            icon="ios-trash-outline"
            size="small"
            type="error"
            v-privilege="'assets-batch-delete'"
            >Batch Delete</Button
          >
        </Row>
        <Table
          :columns="columns"
          :data="tableData"
          :height="tableHeadHeight"
          border
          highlight-row
          ref="mainTable"
        ></Table>
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :page-size-opts="[10, 20, 30, 50, 100]"
          :total="total"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          show-elevator
          show-sizer
          show-total
          class="smart-query-table-page"
        ></Page>
      </Card>
    </div>
    <Modal
      :footer-hide="true"
      :title="saveModal.isUpdate ? 'Update' : 'New'"
      v-model="saveModal.show"
      @on-cancel="saveFormClose"
      width="80%"
    >
      <PeonyListForm
        :isUpdate="saveModal.isUpdate"
        :updateData="saveModal.updateData"
        @on-form-close="saveFormClose"
      />
    </Modal>
    <Modal
      :footer-hide="true"
      title="Select Category"
      v-model="typeModal.show"
      @on-cancel="typeFormClose"
      width="500"
    >
      <TypeListForm
        :isUpdate="typeModal.isUpdate"
        :updateData="mainTableSelectArray"
        @on-form-close="typeFormClose"
      />
    </Modal>
    <Modal
      :footer-hide="true"
      title="Select Label"
      v-model="labelModal.show"
      @on-cancel="labelFormClose"
      width="70%"
    >
      <LabelListForm
        :isUpdate="labelModal.isUpdate"
        :updateData="mainTableSelectArray"
        @on-form-close="labelFormClose"
      />
    </Modal>
        <Modal
      :footer-hide="true"
      :title="!detailModal.isUpdate?'Asset Detail':'Edit'"
      v-model="detailModal.show"
      @on-cancel="detailFormClose"
      width="80%"
    >
      <DetailListForm
        :isUpdate="detailModal.isUpdate"
        :updateData="detailModal.updateData"
        @on-form-close="detailFormClose"
        :show="detailModal.show"
      />
    </Modal>
    <!-- 详情 -->
    <!-- 审核 -->
    <Modal title="Batch Approve" v-model="batchDeleteModal.show" width="450">
      <Form >
        <FormItem>
          <h3 class="error-color">Confirm approve follwing assets：</h3>
        </FormItem>
        <FormItem >
          <Card style="width: 100%; height: 250px; overflow-y: scroll">
            <ul>
              <li v-for="item in mainTableSelectArray" :key="item.id"  v-if="item.publishStatus !='Published'">
                <a href="#">{{ item.name }}</a>
              </li>
            </ul>
          </Card>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="batchDeleteModal.show = false"
          size="small"
          type="default"
          >Cancel</Button
        >
        <Button @click="batchExamine" size="small" type="primary"
          >Confirm</Button
        >
      </div>
    </Modal>
    <!-- 图片放大 -->
    <Modal v-model="imgModelShow" width="470" :footer-hide="true"
    @on-cancel="imgModelShow==false">
      <div><img style="width:450px;height:auto;" :src="srcUrl" /></div>
    </Modal>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { assetsApi } from '@/api/assets.js';
import { labelApi } from '@/api/label';
import PeonyListForm from './components/peony-list-form';
import TypeListForm from './components/type-list-form';
import LabelListForm from './components/label-list-form';
import DetailListForm from './components/detail-list-form';
import { toTreeSelectData } from '@/views/system/base-data/type/components/treeData.js';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import axios from 'axios';
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

const getFile = (url) => {
  return new Promise((resolve, reject) => {
    axios({ method: 'get', url, responseType: 'arraybuffer' })
      .then((data) => {
        resolve(data.data);
      })
      .catch((error) => {
        reject(error.toString());
      });
  });
};

export default {
  name: 'AssetList',
  components: {
    PeonyListForm,
    TypeListForm,
    LabelListForm,
    DetailListForm,
    Treeselect
  },
  props: {},
  data () {
    return {
      saveModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      typeModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      labelModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      detailModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      batchDeleteModal: {
        show: false
      },
      // 数据量
      total: null,
      // 查询参数
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        searchCount: true
      },

      // 表头
      columns: [
        {
          type: 'selection',
          width: 30,
          align: 'center',
        },
        {
          title: 'Asset Name',
          // width: 160,
          align: 'center',
          key: 'name'
        },
        {
          title: 'Category',
          // width: 100,
          align: 'center',
          key: 'category',
          // maxWidth: 360
        },
        {
          align: 'center',
          title: 'Approval Status',
          key: 'publishStatus',
          width: 150
        },
        {
          title: 'Source',
          align: 'center',
          key: 'source',
          width: 80
        }, {
          title: 'Year',
          align: 'center',
          key: 'year',
          width: 80
        }, {
          title: 'File Size',
          align: 'center',
          key: 'fileSize',
          width: 80
        },
        {
          title: 'File Type',
          align: 'center',
          key: 'fileType',
          width: 80
        },
        {
          title: 'Thumbnail',
          align: 'center',
          key: 'content',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.thumbnailUrl
                },
                style: {
                  width: '50px',
                  height: '50px'
                },
                on: {
                  click: () => {
                    this.imgModelShow = true;
                    this.srcUrl = params.row.thumbnailUrl;
                  },
                  mouseenter: () => {
                    this.imgModelShow = true;
                    this.srcUrl = params.row.thumbnailUrl;
                  }
                }
              })
            ]);
          }
        },
        {
          title: 'Action',
          key: 'action',
          width: 140,
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            return h('div', [
              h(
                'a',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showAddDetailForm(params.row);
                    }
                  },
                  directives: [
                    {
                      name: 'privilege',
                      value: 'assets-view'
                    }
                  ]
                },
                'View'
              ),
              h(
                'a',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showEditDetailForm(params.row);
                    }
                  }
                },
                'Edit'
              ),
              h(
                'a',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.remove(params);
                    }
                  }
                },
                'Delete'
              )
            ]);
          }
        }
      ],
      // table数据
      tableData: [],
      // 删除id
      delId: null,
      mainTableSelectArray: [],
      options1: [],
      imgModelShow: false,
      srcUrl: '',
      publishStatusList: []
    };
  },
  computed: {},
  watch: {},
  filters: {},
  created () {
     this.queryList();
     this.getPublishStatusList();
  },
  mounted () {
    this.getTypeList();
  },
  methods: {
    async getPublishStatusList () {
      let res = await assetsApi.getOneGroup({ group: 'publish_status' });
      this.publishStatusList = res.data;
    },
    // 获取类型列表
    getTypeList () {
      assetsApi.getQueryRoot().then(res => {
        console.log('-------------',res)
        this.options1 = toTreeSelectData(res.data);
      });
    },
    // 新增
    addNew () {
      // this.$router.push({ path: "/email/send-mail" });
    },
    // 重置
    reset () {
      this.$refs.searchForm.resetFields();
      this.searchForm.startDate = null;
      this.searchForm.endDate = null;
      this.$set(this.searchForm, 'endDate', null);
      this.find();
    },
    // 删除确定
    async deleteSure (data) {
      this.$Spin.show();
      let res = await assetsApi.delete(data);
      this.$Message.success('Delete Success');
      this.$Spin.hide();
      this.queryList();
    },
    // 删除操作
    deleteEmail () {
      if (!this.validateMainTableSelection()) {
        return;
      }
      let idArray = {
        idArray: this.mainTableSelectArray.map((e) => e.id)
      };
      this.$Modal.confirm({
        title: 'Kindly Reminder',
        content: 'Are you sure to delete the selected items?',
        onOk: () => {
          this.deleteSure(idArray);
        },
        okText: 'Confirm',
        cancelText: 'Cancel'
      });
    },
    remove (data) {
      this.$Modal.confirm({
        title: 'Kindly Reminder',
        content: 'Are you sure to delete the selected items?',
        onOk: () => {
          let idArray = {
            idArray: [data.row.id]
          };
          this.deleteSure(idArray);
        },
        okText: 'Confirm',
        cancelText: 'Cancel'
      });
    },
    // 查询
    find () {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = 10;
      this.queryList();
    },
    // 更改分页查询条数
    changePageSize (pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.queryList();
    },
    // 获取邮件数据
    async queryList () {
      this.$Spin.show();
      let res = await assetsApi.query(this.searchForm);
      this.$Spin.hide();
      this.tableData = res.data.list;
      this.total = res.data.total;
      if (res.data.pages < this.searchForm.pageNum) {
        this.searchForm.pageNum = res.data.pages;
      }
    },
    // 页码改变
    changePage (pageNum) {
      this.searchForm.pageNum = pageNum;
      this.queryList();
    },
    showAddPeonyForm () {
      this.saveModal.isUpdate = false;
      this.saveModal.show = true;
    },
    showEditPeonyForm (updateObject) {
      this.saveModal.isUpdate = true;
      this.saveModal.updateData = updateObject;
      this.saveModal.show = true;
    },
    saveFormClose () {
      this.saveModal.show = false;
      //更新列表
      this.queryList();
    },
    showAddTypeForm () {
      if (!this.validateMainTableSelection()) {
        return;
      }
      this.typeModal.isUpdate = false;
      this.typeModal.show = true;
    },
    showEditTypeForm (updateObject) {
      this.typeModal.isUpdate = true;
      this.typeModal.updateData = updateObject;
      this.typeModal.show = true;
    },
    typeFormClose () {
      this.typeModal.show = false;
      this.mainTableSelectArray = [];
      // this.queryList();
    },
    // 标签
    showAddLabelForm () {
      if (!this.validateMainTableSelection()) {
        return;
      }
      this.labelModal.isUpdate = true;
      this.labelModal.show = true;
    },
    showEditLabelForm (updateObject) {
      if (!this.validateMainTableSelection()) {
        return;
      }
      this.labelModal.isUpdate = true;
      this.labelModal.show = true;
    },
    labelFormClose () {
      this.labelModal.show = false;
      this.mainTableSelectArray = [];
      // this.queryList();
    },
    showBatchDeleteModal () {
      this.mainTableSelectArray = this.$refs.mainTable.getSelection();
      for (let i = 0; i < this.mainTableSelectArray.length; i++) {
        console.log(this.mainTableSelectArray[i]);
        if (this.mainTableSelectArray[i].publishStatus !== 'UnPublished') {
          this.$Message.error('只能选择UnPublished的数据进行审核');
          return;
        }
      }

      if (!this.validateMainTableSelection()) {
        return;
      }
      this.batchDeleteModal.show = true;
    },
    // 校验是否有选中
    validateMainTableSelection () {
      this.mainTableSelectArray = this.$refs.mainTable.getSelection();
      if (this.mainTableSelectArray.length < 1) {
        this.$Message.error('请选择至少一条数据');
        return false;
      }
      return true;
    },
    async batchExamine () {
      this.$Spin.show();
      let param = {

      };
      await assetsApi.audit(
        { idArray: this.mainTableSelectArray.map((e) => e.id) }
      );
      this.batchDeleteModal.show = false;
      this.$Message.success('Approval success');
      this.$Spin.hide();
      this.queryList();
    },
    async batchDownload () {
      if (!this.validateMainTableSelection()) return;
      let arr = [];
      this.mainTableSelectArray.forEach(item => {
        arr.push(item.id);
      });
      await assetsApi.multiDownload({ idArray: arr });
    },
    // 下载
    // async batchDownload () {
    //   if (!this.validateMainTableSelection()) return;
    //   let arr = [];
    //   this.mainTableSelectArray.forEach(item => {
    //     arr.push(item);
    //   });
    //   if (arr.length === 0) {
    //     return this.$Message.error('请选择至少一条数据');
    //   }
    //   if (arr.length === 1) {
    //     if (this.isImageInChromeNotEdge(arr[0].fileType)) { // 判断是否为chrome里的图片
    //       this.imgToDataURL(arr[0].downloadUrl, arr[0].name, arr[0].fileType);
    //     } else {
    //       this.downloadNormalFile(arr[0].downloadUrl, arr[0].name);
    //     }
    //   } else {
    //     this.downloadFileAll(arr);
    //   }
    // },
    downloadFileAll (selectAssets) {
      if (selectAssets.length === 0) {
        return this.$Message.error('请选择至少一条数据');
      }
      console.log(selectAssets);
      this.handleBatchDownload(selectAssets);
    },
    handleBatchDownload (selectedArr) {
      const data = selectedArr.map(j => j.downloadUrl);

      // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
      const zip = new JSZip();
      const cache = {};
      const promises = [];
      data.forEach((item) => {
        const promise = getFile(item).then((data) => {
          console.log('下载文件', item, selectedArr);
          // 下载文件, 并存成ArrayBuffer对象
          // const arr_name = item.split("/");
          const file_name = selectedArr.find(i => item == i.downloadUrl).name
          // 获取文件名
          zip.file(file_name, data, { binary: true });
          // 逐个添加文件
          cache[file_name] = data;
        });
        promises.push(promise);
      });
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then((content) => {
          // 生成二进制流
          FileSaver.saveAs(content, "素材.zip");
          // 利用file-saver保存文件
        });
      });
    },
    isImageInChromeNotEdge (fType) {
      let bool = false;
      if ((window.navigator.userAgent.indexOf('Chrome') !== -1 && window.navigator.userAgent.indexOf('Edge') === -1) &&
          (fType === 'JPG' || fType === 'GIF' || fType === 'PNG' || fType === 'BMP' || fType === 'JPEG' || fType === 'SVG' || fType === 'TIF'))
        return true;
    },
    downloadNormalFile (src, filename) {
      console.log('normal file downlaod...' + filename);
      let x = new XMLHttpRequest();
      x.open('GET', src, true);
      x.responseType = 'blob';
      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.style.display = 'none';
        document.body.appendChild(link); // 添加到页面中，为兼容Firefox浏览器
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link); // 从页面移除
      };
      x.send();
    },
    imgToDataURL (url, filename, fileType) {
      this.getBase64(url, fileType, (_baseUrl) => {
        // 创建隐藏的可下载链接
        let eleLink = document.createElement('a');
        eleLink.download = filename;
        eleLink.style.display = 'none';
        // 图片转base64地址
        eleLink.href = _baseUrl;
        // 触发点击
        document.body.appendChild(eleLink);
        eleLink.click();
        // 然后移除
        document.body.removeChild(eleLink);
      });
    },
    getBase64 (url, fileType, callback) {
      console.log('base64 downlaod...');
      // 通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片
      // eslint-disable-next-line one-var
      let Img = new Image(),
        dataURL = '';
      Img.src = url;
      Img.setAttribute('crossOrigin', 'Anonymous');
      Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
        let canvas = document.createElement('canvas'), // 创建canvas元素
          width = Img.width, // 确保canvas的尺寸和图片一样
          height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中
        dataURL = canvas.toDataURL('image/' + fileType); // 转换图片为dataURL
        callback ? callback(dataURL) : null;
      };
    },
    // 详情
    showAddDetailForm (data) {
      this.detailModal.isUpdate = false;
      this.detailModal.show = true;
      this.detailModal.updateData = data;
    },
    showEditDetailForm (updateObject) {
      console.log(updateObject);
      this.detailModal.isUpdate = true;
      this.detailModal.updateData = updateObject;
      this.detailModal.show = true;
    },
    detailFormClose () {
      this.detailModal.show = false;
      // this.queryList();
    },
    loadOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        assetsApi.getQueryChildren({ id: parentNode.id }).then((res) => {
          if (res.data && res.data.length) {
            res.data.forEach(item =>  item.label = item.title)
            parentNode.children = res.data
            callback();
          }else {
            parentNode.children = []
            callback();
          }
        });
      }
    },
  }
};
</script>
<style lang="less" scoped>
/deep/ .vue-treeselect__control {
    display: inline-block!important;
}
</style>
